package com.sunma.receive.service.impl;

import com.sunma.assets.domain.Assets;
import com.sunma.assets.mapper.AssetsMapper;
import com.sunma.assets.service.IAssetsService;
import com.sunma.common.core.domain.AjaxResult;
import com.sunma.common.core.domain.entity.SysUser;
import com.sunma.common.core.domain.model.LoginUser;
import com.sunma.common.exception.ServiceException;
import com.sunma.common.utils.DateUtils;
import com.sunma.common.utils.ExceptionUtil;
import com.sunma.common.utils.SecurityUtils;
import com.sunma.common.utils.StringUtils;
import com.sunma.framework.security.context.PermissionContextHolder;
import com.sunma.receive.domain.AssetsReceive;
import com.sunma.receive.mapper.AssetsReceiveMapper;
import com.sunma.receive.service.IAssetsReceiveService;
import com.sunma.repair.domain.AssetsRepair;
import com.sunma.repair.mapper.AssetsRepairMapper;
import com.sunma.repair.service.IAssetsRepairService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 资产领用明细Service业务层处理
 *
 * @author sunma
 * @date 2024-07-08
 */
@Service
public class AssetsReceiveServiceImpl implements IAssetsReceiveService {
    @Resource
    private AssetsReceiveMapper assetsReceiveMapper;

    @Resource
    private IAssetsService assetsService;

    @Resource
    private AssetsRepairMapper assetsRepairMapper;

    /**
     * 查询资产领用明细
     *
     * @param id 资产领用明细主键
     * @return 资产领用明细
     */
    @Override
    public AssetsReceive selectAssetsReceiveById(Long id) {

        return assetsReceiveMapper.selectAssetsReceiveById(id);
    }

    /**
     * 查询资产领用明细列表
     *
     * @param assetsReceive 资产领用明细
     * @return 资产领用明细
     */
    @Override
    public List<AssetsReceive> selectAssetsReceiveList(AssetsReceive assetsReceive) {

        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (StringUtils.isNotNull(loginUser)) {
            SysUser currentUser = loginUser.getUser();
            // 如果是超级管理员，则不过滤数据
            if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin()) {
                assetsReceive.setUserId(currentUser.getUserId());
            }
        }

        // 返回根据权限过滤后的结果
        return assetsReceiveMapper.selectAssetsReceiveList(assetsReceive);
    }

    /**
     * 新增资产领用明细
     *
     * @param assetsReceive 资产领用明细
     * @return 结果
     */
    @Override
    public int insertAssetsReceive(AssetsReceive assetsReceive) {
        /* // 设置资产领用明细中的用户ID，需要用标准SecurityContextHolder的方式获取
        Long userId = null;
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof LoginUser) {
            userId = ((LoginUser) principal).getUser().getUserId();  // 获取用户ID，表示当前用户id就是领用人id
        }*/
        // System.out.println("userId: " + userId);
        Assets assets = assetsService.selectAssetsById(assetsReceive.getAssetsId());
        if (assets.getNum() <= 0) {
            // 抛出异常
            throw new ServiceException("资产数量不足");
        }
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser currentUser = null;
        if (StringUtils.isNotNull(loginUser)) {
            currentUser = loginUser.getUser();
            // 如果是超级管理员，则不过滤数据
            // if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin())

            if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin()) {

                assetsReceive.setUserId(currentUser.getUserId());
            } else {
                // 抛出异常
                throw new ServiceException("不能以管理员权限申请物资领用");
            }
        }

        //assetsReceive.setUserId(userId);
        assetsReceive.setDate(DateUtils.getNowDate());
        assetsReceive.setStatus(String.valueOf(0));
        assetsReceive.setReturnStatus(String.valueOf(0));

        return assetsReceiveMapper.insertAssetsReceive(assetsReceive);
    }

    /**
     * 修改资产领用明细
     *
     * @param assetsReceive 资产领用明细
     * @return 结果
     */
    @Override
    public int updateAssetsReceive(AssetsReceive assetsReceive) {
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser currentUser = null;
        if (StringUtils.isNotNull(loginUser)) {
            currentUser = loginUser.getUser();
            // 如果是超级管理员，则不过滤数据
            // if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin())

            if (StringUtils.isNotNull(currentUser) && currentUser.isAdmin()&&"1".equals(assetsReceive.getStatus())) {
                    Assets assets = assetsService.selectAssetsById(assetsReceive.getAssetsId());
                    if (assets.getNum() > 0) {
                        assets.setNum(assets.getNum() - 1);
                        int updated = assetsService.updateAssets(assets);
                        if (updated < 0) {
                            throw new ServiceException("资产出库失败！");
                        }
                    } else {
                        throw new ServiceException("库存不足，无法出库！");
                    }
            }
        }
        return assetsReceiveMapper.updateAssetsReceive(assetsReceive);
}

    /**
     * 批量删除资产领用明细
     *
     * @param ids 需要删除的资产领用明细主键
     * @return 结果
     */
    @Override
    public int deleteAssetsReceiveByIds(Long[] ids) {
        return assetsReceiveMapper.deleteAssetsReceiveByIds(ids);
    }

    /**
     * 删除资产领用明细信息
     *
     * @param id 资产领用明细主键
     * @return 结果
     */
    @Override
    public int deleteAssetsReceiveById(Long id) {
        return assetsReceiveMapper.deleteAssetsReceiveById(id);
    }

    @Override
    public int updateAssetsReceiveByReturnData(AssetsReceive assetsReceive) {
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser currentUser = null;
        if (StringUtils.isNotNull(loginUser)) {
            currentUser = loginUser.getUser();
/* */       AssetsRepair assetsRepair = assetsRepairMapper.selectAssetsRepairByReceiveId(assetsReceive.getId());

            if (assetsRepair!=null&&"1".equals(assetsRepair.getStatus())){
                throw new ServiceException("当前物资正在维修中，不能进行入库处理。");
            }
            if (currentUser.isAdmin()&&"1".equals(assetsReceive.getReturnStatus())) {
                //if ("1".equals(assetsReceive.getReturnStatus())) { // 如果归还状态为“已归还”
                Assets assets = assetsService.selectAssetsById(assetsReceive.getAssetsId());
                assets.setNum(assets.getNum() + 1);
                int updated = assetsService.updateAssets(assets);
                if (updated < 0) {
                    throw new ServiceException("添加回库失败！");
                }
            }

        }

        return assetsReceiveMapper.updateAssetsReceive(assetsReceive);
    }
}
